# -*- coding: utf-8 -*-

import time
import random
from datetime import date
from time import sleep

from celery import shared_task

# 没有使用@project_app.task，而是使用@shared_task，也要导入from project.app import project_app
from project.app import project_app
from util.task_util import timer
import logging

logger = logging.getLogger(__name__)


# @project_app.task()
@shared_task()
def task(*args, **kwargs):
    logger.info(f'task({args},{kwargs})')
    return 'SUCCESS'


@shared_task(name='schedule_task_name')
def schedule_task_func(a: int, b: int):
    logger.info('schedule task')
    return a + b


@shared_task(bind=True, serializer='json')
def bind_self_task(self, a: int, b: int):
    logger.info('task1')
    timeout = random.randint(4, 8)
    self.update_state(state="PROGRESS", meta={'progress': 50})
    logger.info('task1:timeout:' + str(timeout))
    time.sleep(timeout)
    self.update_state(state="PROGRESS", meta={'progress': 90})
    return a + b


@shared_task(bind=True, max_retries=30, default_retry_delay=30)
def retry_task(self, retry_flag=False):
    """
    任务重启
    :param self:
    :param retry_flag:
    :return:
    """
    logger.info('start')
    try:
        sleep(10)
        logger.info('raise error')
        if retry_flag:
            raise Exception('message')

    except Exception as e:
        logger.error(f'error:{repr(e)},delay time,task retry.', exc_info=True)
        sleep(10)
        logger.info('sleep end,retry task.')
        self.retry(exc=e)


@shared_task(bind=True, )
@timer
def sleep_task(self, task_name):
    logger.info(f'{task_name} start')
    sleep(10)
    logger.info(f'{task_name} sleep 10s')
    sleep(10)
    logger.info(f'{task_name} end')
    return 'SUCCESS'

#
# @project_app.task(bind=True)
# def task_func(self, args_name: str, kwargs_name: str = '', ):
#     logger.info(f'args_name={args_name},kwargs_name={kwargs_name}.')
#     return 'OK'
